package com.dingpeikeji.quickdeer.modules.jpush.web;

import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.dingpeikeji.quickdeer.core.common.persistence.Page;
import com.dingpeikeji.quickdeer.core.common.web.BaseController;
import com.dingpeikeji.quickdeer.modules.jpush.entity.TPush;
import com.dingpeikeji.quickdeer.modules.jpush.service.TPushService;

@Controller
@RequestMapping(value = "${adminPath}/push/tPush")
public class JPushController extends BaseController {

	@Autowired
	private TPushService tPushService;
	
	@RequestMapping(value = {"list", ""})
	public String list(TPush tPush,String message, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<TPush> page= tPushService.findPage(new Page<TPush>(request, response), tPush);
		if(message==null){
			message=request.getParameter("message");
		}
		if (StringUtils.isNoneEmpty(message)) {
			if(message.equals("0")){
				model.addAttribute("message", "删除成功");
			}else if(message.equals("1")){
				model.addAttribute("message", "推送成功");
			}
		}
		model.addAttribute("page", page);
		return "modules/push/tPushList";
	}
	
	@RequestMapping(value = "form")
	public String form(TPush tPush, Model model) {
		if(tPush.getPushid()!=null){
			tPush=tPushService.get(tPush.getPushid());
		}
		model.addAttribute("tPush", tPush);
		return "modules/push/tPushForm";
	}
	
	@RequestMapping(value = "del")
	public String del(TPush tPush, Model model) {
		if(tPush.getPushid()!=null){
			tPushService.delete(tPush);
		}
		return "redirect:list?message=0";
	}
	
	@RequestMapping(value = "add")
	public String add(TPush tPush, Model model) {
		model.addAttribute("tPush", tPush);
		return "modules/push/tPushAdd";
	}
	
	@RequestMapping(value = "send")
	public String use(TPush tPush, HttpServletRequest request, HttpServletResponse response, Model model) {
		tPush.setCreateDate(new Date());
		tPush.setPushid(UUID.randomUUID().toString().replace("-", "").toUpperCase());
		tPushService.save(tPush);
		JiguangPush.push(tPush.getMessage());
		return "redirect:list?message=1";
	}

}